package org.canx.controller;

import org.canx.service.LoginService;
import org.canx.service.TokenService;
import org.canx.utils.ConstantCommon;
import org.canx.utils.Response;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.view.RedirectView;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletResponse;

/**
 * @class description : 登录Contrller
 *
 * @author Enough Wang
 * @time 2017年7月25日
 */

@RestController
@RequestMapping("/login")
public class LoginController {

    private static Logger logger = Logger.getLogger(LoginController.class);

    @Autowired
    LoginService loginService ;
    @Autowired
    TokenService tokenService;

    //员工Code登陆
    @PostMapping("/code")
    public Response loginByCode(String userId, HttpServletResponse re) {
        logger.info("You are visiting : /login/code");
        Response response = loginService.checkCode(userId, re);
        return response;
    }

    //员工密码登陆
    @PostMapping ("/pass")
    public Response loginByPass(String userId ,String pass, HttpServletResponse rs) {
        logger.info("You are visiting : /login/pass");
        Response response = loginService.checkPass(userId, pass, rs);
        return response;
    }

    @RequestMapping("/setck")
    public ModelAndView setck(HttpServletResponse response, String token){

        if (token != null) {
            if(tokenService.checkTokenIsExist(token) > 1) {

                Cookie ck = new Cookie("P-TOKEN", token);
                ck.setDomain(ConstantCommon.FRONT_DOMAIN);
                ck.setPath("/");
                response.addCookie(ck);
            }

        }
        return new ModelAndView(new RedirectView(ConstantCommon.FRONT_HOME_URL));
    }

    @RequestMapping("/test")
    public String test(){
        return "test";
    }
}
